#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
typedef long long ll;
typedef unsigned long long ull;
#define rep(i,a,b) for(register ll i = (a);i <= (b);++i)
#define per(i,a,b) for(register ll i = (a);i >= (b);--i)  
using std::string;using std::cin;using std::cout;
using std::priority_queue;

//pair<dep,num>
priority_queue<std::pair<ll,ll> > a_zheng;
priority_queue<std::pair<ll,ll> > a_fu;

const ll N = 2e5+5;
ll a[N],b[N],ans,p[N],cnt;
ll head[N],next[N],ver[N],tot,dep[N];
inline void link(ll x,ll y){ver[++tot] = y , next[tot] = head[x] , head[x] = tot;}
ll n;
inline void dfs(ll now,ll father){
	dep[now] = dep[father] + 1;
	for(ll i = head[now];i;i = next[i]){
		if(ver[i] == father) continue;
		dfs(ver[i],now);
	}
}

int main(){
	dep[0] = -1 , cnt = 0;
	std::ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	//freopen("in.in", "r", stdin);
	cin >> n;
	while(a_zheng.size()) a_zheng.pop();
	while(a_fu.size()) a_fu.pop();
	rep(i,1,n) cin >> a[i];
	rep(i,1,n) cin >> b[i];
	rep(i,1,n) dep[i] = 0;
	rep(i,1,n){
		if(b[i] < 0) continue;
		link(b[i],i);
		dep[i] = -1;
	}
	rep(i,1,n){
		if(dep[i] == 0) dfs(i,0);
		else continue;
	}
	rep(i,1,n) if(a[i] >= 0) a_zheng.push(std::make_pair(dep[i],i));
	while(a_zheng.size()){
		std::pair<ll,ll> now = a_zheng.top();a_zheng.pop();
		ans += a[now.second] , a[ b[now.second] ] += a[now.second];
		p[++cnt] = now.second;
		if(a[ b[now.second] ] - a[now.second] < 0 && a[ b[now.second] ] >= 0) a_zheng.push(std::make_pair(dep[ b[now.second] ],b[now.second]));
	}
	rep(i,1,n) if(a[i] < 0) a_fu.push(std::make_pair(-dep[i],i));
	while(a_fu.size()){
		std::pair<ll,ll> now = a_fu.top();a_fu.pop();
		ans += a[now.second] , a[ b[now.second] ] += a[now.second];
		p[++cnt] = now.second;
	}
	cout << ans << "\n";
	rep(i,1,cnt) cout << p[i] << " ";
	cout << "\n";
	return 0;
}